#include <myMuduo/TcpServer.h>
#include <myMuduo/Logger.h>

#include <string>
#include <functional>
#include <iostream>

class EchoServer
{
public:
    EchoServer(EventLoop *loop, const InetAddress &addr, const std::string &name)
        : loop_(loop)
        , server_(loop, addr, name)
    {
        // 注册回调函数
        server_.setConnectionCallback(std::bind(&EchoServer::onConnection, this, std::placeholders::_1));

        server_.setMessageCallback(std::bind(&EchoServer::onMessage, this,
                                             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        // 设置线程数量
        server_.setThreadNum(3);
        server_.EnableInactiveRelease(10);
    }

    void start()
    {
        server_.start();
        // server_.runAfter(std::bind(&EchoServer::print, this), 15);
    }

    void print()
    {
        std::cout<<"-------------------定时任务---------------"<<std::endl;
    }

private:
    // 连接回调
    void onConnection(const TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            LOG_INFO("Connection UP : %s", conn->peerAddress().toIpPort().c_str());
        }
        else
        {
            LOG_INFO("Connection DOWN : %s", conn->peerAddress().toIpPort().c_str());
        }
    }

    // 有读写消息时的回调
    void onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp recivetime)
    {
        std::string msg = buf->retrieveAllAsString();
        conn->send(msg);
        // conn->shutdown();   //测试。这里发完直接关闭写端
    }

    EventLoop *loop_;
    TcpServer server_;
};

int main()
{
    EventLoop loop; //mainloop
    InetAddress localAddr(6666);    //本地地址，ip地址缺省值为"127.0.0.1"
    EchoServer server(&loop, localAddr, "EchoServer-01");
    server.start();     
    loop.loop();    //启动mainloop的poller，监听新连接

    return 0;
}